// 轮播图管理云函数 - 合并所有管理功能
const db = uniCloud.database();
const _ = db.command;

// 管理员权限验证
async function checkAdminPermission(context) {
  const openid = context?.OPENID || '';
  
  // 查询管理员集合
  const adminRes = await db.collection('admin')
    .where({ openid: openid })
    .get();
  
  // if (adminRes.data.length === 0) {
  //   throw new Error('无管理员权限');
  // }
  
  return true;
}

// 获取轮播图列表
async function getBanners(context) {
  await checkAdminPermission(context);
  
  const res = await db.collection('banners')
    .orderBy('sort', 'asc')
    .get();
  
  return {
    code: 200,
    data: res.data,
    message: '获取轮播图列表成功'
  };
}

// 添加轮播图
async function addBanner(event, context) {
  await checkAdminPermission(context);
  
  const { title, imageUrl,description, linkType, linkId, linkUrl, sort, status } = event;
  
  // 参数校验
  if (!title || !imageUrl ) {
    throw new Error('标题、图片和链接类型为必填项');
  }
  
  // 链接类型验证
  if (linkType === 'category' || linkType === 'detail') {
    if (!linkId) {
      throw new Error('分类或详情链接必须提供linkId');
    }
  } else if (linkType === 'page' || linkType === 'external') {
    if (!linkUrl) {
      throw new Error('页面或外部链接必须提供linkUrl');
    }
  }
  
  // 添加轮播图
  const now =new Date()
  const res = await db.collection('banners').add({
      title,
      imageUrl,
      description,
      linkType,
      linkId: linkId || '',
      linkUrl: linkUrl || '',
      sort: sort || 0,
      status: status !== undefined ? status : true,
      createTime: now,
      updateTime: now
  });
  
  return {
    code: 200,
    data: { _id: res._id },
    message: '添加轮播图成功'
  };
}

// 更新轮播图
async function updateBanner(event, context) {
  await checkAdminPermission(context);
  
  const { _id, title,description, imageUrl, linkType, linkId, linkUrl, sort, status } = event;
  
  // 参数校验
  if (!_id) {
    throw new Error('轮播图ID不能为空');
  }
  
  if (title === undefined && imageUrl === undefined && linkType === undefined &&description === undefined && 
      linkId === undefined && linkUrl === undefined && sort === undefined && status === undefined) {
    throw new Error('至少需要更新一个字段');
  }
  
  // 链接类型验证
  if (linkType !== undefined) {
    if (linkType === 'category' || linkType === 'detail') {
      if (!linkId) {
        throw new Error('分类或详情链接必须提供linkId');
      }
    } else if (linkType === 'page' || linkType === 'external') {
      if (!linkUrl) {
        throw new Error('页面或外部链接必须提供linkUrl');
      }
    }
  }
  
  // 构建更新数据
  const updateData = { updateTime: new Date() };
  if (title !== undefined) updateData.title = title;
  if (imageUrl !== undefined) updateData.imageUrl = imageUrl;
  if (description !== undefined) updateData.description = description;
  if (linkType !== undefined) updateData.linkType = linkType;
  if (linkId !== undefined) updateData.linkId = linkId;
  if (linkUrl !== undefined) updateData.linkUrl = linkUrl;
  if (sort !== undefined) updateData.sort = sort;
  if (status !== undefined) updateData.status = status;
  
  // 更新轮播图
  await db.collection('banners').doc(_id).update({
    ...updateData
  });
  
  return {
    code: 200,
    message: '更新轮播图成功'
  };
}

// 更新轮播图状态
async function updateBannerStatus(event, context) {
  await checkAdminPermission(context);
  
  const { _id, status } = event;
  
  // 参数校验
  if (!_id || status === undefined) {
    throw new Error('轮播图ID和状态不能为空');
  }
  
  // 更新状态
  await db.collection('banners').doc(_id).update({
      status,
      updateTime: new Date()
  });
  
  return {
    code: 200,
    message: '更新轮播图状态成功'
  };
}

// 删除轮播图
async function deleteBanner(event, context) {
  await checkAdminPermission(context);
  
  const { _id } = event;
  
  // 参数校验
  if (!_id) {
    throw new Error('轮播图ID不能为空');
  }
  
  // 检查轮播图是否存在
  const bannerRes = await db.collection('banners').doc(_id).get();
  if (!bannerRes.data) {
    throw new Error('轮播图不存在');
  }
  
  // 删除轮播图
  await db.collection('banners').doc(_id).remove();
  
  return {
    code: 200,
    message: '删除轮播图成功'
  };
}

// 主入口函数
exports.main = async (event, context) => {
  try {
    const { action } = event;
    
    switch (action) {
        case 'getList':
          return await getBanners(context);
        case 'add':
          return await addBanner(event, context);
        case 'update':
          return await updateBanner(event, context);
        case 'updateStatus':
          return await updateBannerStatus(event, context);
        case 'delete':
          return await deleteBanner(event, context);
        default:
          throw new Error('无效的操作类型');
      }
  } catch (error) {
    return {
      code: 400,
      message: error.message || '操作失败'
    };
  }
};